<script setup>
import {dataImportApi} from "@/apis/CMS/batchDataImport/index.js";
import {madeTypeMixins} from "@/mixins/index.js";
import {apiParam} from "@/utils/index.js";
import {getNowDate} from "@/utils/time.js";
import {skyMsgError, skyMsgSuccess} from "@/utils/sky.js";

import {ElLoading} from 'element-plus';

const skyExcelRef = ref();
const formRef = ref();
const pageData = ref({
  dataImportParma: {
    DicTypeCode: "import_cate",
  },
  form: {
    cate: "",
    start: 1,
    column: 1,
    end: 1,
  },
  rules: {
    cate: [{required: true, message: "请选择导入分类", trigger: "blur"}],
  },
  pageParams: {
    pageNo: 1,
    SortFields: "FDicTypeCode",
    direction: "asc",
    pageSize: 1000
  },
  paramsList: [],
  cateList: [],
  excelColumns: [],
  excelList: [],
  tableList: [],
  selectList: [],
  errorColumns: [],
  errorList: [],
});
const method = reactive({
  /** 一次性获取全部参数 */
  handleListParams: async () => {
    const data = apiParam("2.0", "CMS.ParametersDAL.Querybypage",
      [
        {ParaType: "", ParaCode: "", ParaName: ""},
        {direction: "asc", pageNo: 1, pageSize: 1000000, sortBy: "FParaCode"},
      ]);
    try {
      const res = await dataImportApi(data);
      pageData.value.paramsList = res.data.data;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 获取指定参数 */
  handleByParaName: (paraName) => {
    const param = pageData.value.paramsList.find(item => item.ParaName === paraName);
    if (param) {
      return pageData.value.paramsList.find(item => item.ParaName === paraName);
    } else {
      return {};
    }
  },
  /** 获取导入分类 */
  handleCateList: async () => {
    const cateList = [
      {DicCode: "BOM", DicName: "BOM"},
      {DicCode: "工艺", DicName: "工艺"},
      {DicCode: "物料", DicName: "物料"},
    ];
    const data = apiParam("2.0", "CMS.DictionaryDAL.Querybypage",
      [pageData.value.dataImportParma, pageData.value.pageParams]);
    try {
      const res = await dataImportApi(data);
      pageData.value.cateList = res.data.data.length > 0 ? res.data.data : cateList;
    } catch (error) {
      skyMsgError("数据查询失败，请刷新重试🌻");
    }
  },
  /** 文件excel导入 */
  handleImportExcel: () => {
    if (!formRef.value) return;
    (formRef.value).validate(async (valid) => {
      if (valid) {
        let params = {
          isApi: false, // 是否后台上传
        };
        skyExcelRef.value.excelParams(params);
        // if (Array.isArray(val)) {
        //   // 判断分类
        //   if (pageData.value.form.cate.includes("BOM")) {
        //     importProduct(val);
        //   } else if ((pageData.value.form.cate.includes("工艺"))) {
        //     importProduct(val);
        //   } else if ((pageData.value.form.cate.includes("物料"))) {
        //     importProduct(val);
        //   }
        // }
      } else {
        skyMsgError("验证失败，请先选择导入分类🌻");
      }
    });
  },
  /** 文件excel上传 */
  handleConfirm: (val) => {
    // 获取表头
    pageData.value.excelColumns = val.tableCustom;
    // 获取数据
    pageData.value.excelList = val.tableList;
  },
  /** 选择导入数据 */
  handleSelectionChange: (selection) => {
    pageData.value.selectList = [...selection];
  },
  /** 保存数据 */
  handleImport: async () => {
    const loading = ElLoading.service({
      lock: true,
      text: '数据保存中...',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    let successNum = 0;
    if (pageData.value.selectList.length > 0) {
      if (pageData.value.form.cate.includes("BOM")) {
        const field = {

        };
      } else if (pageData.value.form.cate.includes("工艺")) {

      } else if (pageData.value.form.cate.includes("物料")) {
        const field = {
          "序号": "Sort",
          "分类编码": "ProTypeCode",
          "料号": "ProductCode",
          "物料名称": "ProductName",
          "规格型号": "ProductSpec",
          "计量单位": "UnitCode",
          "形态属性": "MadeType",
          "存储地点": "MainWhName",
        };
        for (let i = 0; i < pageData.value.selectList.length; i++) {
          const item = pageData.value.selectList[i];
          let product = {BillDate: getNowDate(), Items: []};
          // 料号存在跳过
          const dataId = apiParam("2.0", "PLM.ProductsDAL.Querybykeyvalue",
            [item['料号'], {
              pageNo: 1, sortBy: "FProTypeCode", direction: "asc", pageSize: 5,
            }]);
          const res = await dataImportApi(dataId);
          if (res.data.recordsTotal === 0) {
            // 添加单头
            for (const attr in item) {
              product[field[attr]] = item[attr];
              // 添加子表
              if (attr === "是否有图" || attr === "转换率" ||
                attr === "批号参数" || attr === "是否请购" ||
                attr === "质检方案" || attr === "财务分类" ||
                attr === "收货程序") {
                product.Items.push({
                  SeqNo: 1,
                  ParaName: attr,
                  ParaValue: method.handleByParaName(attr).ParaCode || attr,
                  NameValue: item[attr],
                  IsParameter: method.handleByParaName(attr).ParaSourceType === "字典" ? 1 : 0 || 0,
                  Remark: "",
                });
              }
            }
            product.MadeType = madeTypeMixins(product.MadeType).value || "";
            // 一条条新增
            const data = apiParam("2.0", "PLM.ProductsDAL.Create", [product]);
            const res = await dataImportApi(data);
            if (res.status >= 0) {
              // 成功删除
              [].splice(i, 1);
              successNum++;
            } else {
              // 失败删除
              pageData.value.errorList.push(item);
              pageData.value.errorColumns = Object.keys(pageData.value.errorList[0]);
              [].splice(i, 1);
            }
          } else {
            // 料号已存在
            item['错误信息'] = "料号与存在";
            pageData.value.errorList.push(item);
            pageData.value.errorColumns = Object.keys(pageData.value.errorList[0]);
          }
        }
        skyMsgSuccess(`操作成功，成功导入${successNum}条数据！`);
      }
    } else {
      skyMsgError("请选择导入数据");
    }
    loading.close();
  },
  /** 下载模板 */
  handleTemplateExcel: () => {
    skyMsgError("暂无下载模板哟🌻");
    // window.location.href = import.meta.env.VITE_SERVER + "/excelTemplate";
  },
  /** 导出错误数据 */
  handleErrorDownload: () => {
  },
});
onMounted(() => {
  method.handleListParams();
  method.handleCateList();
});
</script>

<!-- 数据导入-->
<template>
  <div class="sky-flex">
    <SkyCard>
      <!-- 搜索条件 -->
      <el-form ref="formRef" :rules="pageData.rules" :model="pageData.form" label-width="80px" status-icon>
        <el-row>
          <el-form-item label="导入分类" prop="cate">
            <el-select style="width: 240px" v-model="pageData.form.cate" clearable>
              <el-option v-for="(item, index) in pageData.cateList" :key="index"
                         :label="item.DicCode" :value="item.DicName"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="起始行" prop="start">
            <el-input-number style="width: 100%;" v-model="pageData.form.start"/>
          </el-form-item>
          <el-form-item label="起始列" prop="column">
            <el-input-number style="width: 100%;" v-model="pageData.form.column"/>
          </el-form-item>
          <el-form-item label="截止列" prop="end">
            <el-input-number style="width: 100%;" v-model="pageData.form.end"/>
          </el-form-item>
        </el-row>
      </el-form>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="info" icon="upload" plain @click="method.handleImportExcel">导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="download" plain @click="method.handleImport">保存</el-button>
        </el-col>
      </el-row>
      <!-- excel导入 -->
      <SkyExcel ref="skyExcelRef" @handleTemplateExcel="method.handleTemplateExcel"
                @handleConfirmUpload="method.handleConfirm"></SkyExcel>
      <br/>
      <!-- 导入数据表格 -->
      <el-table
        :data="pageData.excelList"
        empty-text="暂时没有数据哟🌻"
        border
        @selection-change="method.handleSelectionChange"
      >
        <el-table-column type="selection" align="center"/>
        <el-table-column
          v-for="item in pageData.excelColumns"
          :key="item"
          :label="item"
          :prop="item"
          align="center"
          :show-overflow-tooltip="true"
        />
      </el-table>
      <br/>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-button type="danger" icon="Download" plain @click="method.handleErrorDownload()">
          错误数据导出
        </el-button>
      </el-row>
      <br/>
      <!-- 错误数据表格 -->
      <el-table
        :data="pageData.errorList"
        empty-text="暂时没有数据哟🌻"
        border
      >
        <el-table-column type="selection" align="center"/>
        <el-table-column
          v-for="item in pageData.errorColumns"
          :key="item"
          :label="item"
          :prop="item"
          align="center"
          :show-overflow-tooltip="true"
        />
      </el-table>
    </SkyCard>
  </div>
</template>

<style scoped lang="scss">

</style>
